package examples

import java.net._
import java.io._
import org.offsync.nio._
import org.offsync.rich._
import org.offsync.util._

object EchoClient {
  def main(args : Array[String]) : Unit = {
    if (args.length != 2) {
      System.err.println("Usage: server <host> <port>")
      exit(1)
    }
    
    val host = args(0)
    val port = args(1).toInt
    
    new IoService().using { ioService =>
      var quit = false
      val socket = new Socket(host, port)
      val inReader = new BufferedReader(new InputStreamReader(System in))
      val inStream = Stream.continually {
        val line: String = inReader.readLine()
        line
      }
      val os = new PrintStream(socket.getOutputStream)
      val is = new BufferedReader(new InputStreamReader(socket.getInputStream))
      try {
        for (line <- inStream.takeWhile { line => line != "quit" && line != null }) {
          os.println(line)
          println("out: " + is.readLine())
        }
      } finally {
        socket.close()
      }
      /*SocketChannel.open("localhost", 1234).using { clientChannel =>
        val window = Window to (new Array[Byte](100))
        def performRead(): Unit = clientChannel.read(ioService, window) { getBytesRead =>
          try {
            val bytesRead = getBytesRead()
            val readString = new String(window.until(bytesRead).asString())
            performRead()
          } catch {
            case e => System.err.println("client: unexpected exception: " + e)
          }
        }
        performRead()
        clientChannel.write(ioService, "Hello world".window) { getBytesWritten =>
          try {
            val bytesWritten1 = getBytesWritten()
            clientChannel.write(ioService, "Bye!".window) { getBytesWritten2 =>
              try {
                val bytesWritten2 = getBytesWritten2()
              } catch {
                case e => System.err.println("client: unexpected exception: " + e)
              }
            }
          } catch {
            case e => System.err.println("client: unexpected exception: " + e)
          }
        }
      }*/
    }
  }
}
